﻿using System;
using System.Reflection;

namespace Terraria.ModLoader.IO
{
	// Token: 0x020002D9 RID: 729
	internal class TagSerializableSerializer<T> : TagSerializer<T, TagCompound> where T : TagSerializable
	{
		// Token: 0x06001C16 RID: 7190 RVA: 0x00433240 File Offset: 0x00431440
		public TagSerializableSerializer()
		{
			Type typeFromHandle = typeof(T);
			FieldInfo field = typeFromHandle.GetField("DESERIALIZER");
			if (field != null)
			{
				if (field.FieldType != typeof(Func<TagCompound, T>))
				{
					throw new ArgumentException(string.Format("Invalid deserializer field type {0} in {1} expected {2}.", field.FieldType, typeFromHandle.FullName, typeof(Func<TagCompound, T>)));
				}
				this.deserializer = (Func<TagCompound, T>)field.GetValue(null);
			}
		}

		// Token: 0x06001C17 RID: 7191 RVA: 0x004332C4 File Offset: 0x004314C4
		public override TagCompound Serialize(T value)
		{
			TagCompound tagCompound = value.SerializeData();
			tagCompound["<type>"] = value.GetType().FullName;
			return tagCompound;
		}

		// Token: 0x06001C18 RID: 7192 RVA: 0x00433300 File Offset: 0x00431500
		public override T Deserialize(TagCompound tag)
		{
			if (tag.ContainsKey("<type>") && tag.GetString("<type>") != this.Type.FullName)
			{
				Type type = TagSerializer.GetType(tag.GetString("<type>"));
				TagSerializer tagSerializer;
				if (type != null && this.Type.IsAssignableFrom(type) && TagSerializer.TryGetSerializer(type, out tagSerializer))
				{
					return (T)((object)tagSerializer.Deserialize(tag));
				}
			}
			if (this.deserializer == null)
			{
				throw new ArgumentException(string.Format("Missing deserializer for type '{0}'.", this.Type.FullName));
			}
			return this.deserializer(tag);
		}

		// Token: 0x040018A6 RID: 6310
		private Func<TagCompound, T> deserializer;
	}
}
